package wang.unclecat.testtextfield.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ScrollView;
import ohos.agp.components.Text;
import ohos.agp.utils.Point;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import timber.log.Timber;
import wang.unclecat.testtextfield.ResourceTable;
import wang.unclecat.testtextfield.dialog.CustomDialog;
import wang.unclecat.textfieldhelper.TextFieldHelper;
import wang.unclecat.textfieldhelper.impl.ScrollViewTFHAdapter;

import java.util.Optional;

public class MainAbilitySliceScroll extends AbilitySlice {

    private TextFieldHelper textFieldHelper = new TextFieldHelper(new ScrollViewTFHAdapter(){
        @Override
        public int offset() {
            return 110;
        }
    });

    ScrollView rootScrollView;
    private int count = 0;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main_scroll);

        Text helloText = (Text) findComponentById(ResourceTable.Id_text_helloworld);

        bindClick();
        Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(getContext());
        Point pt = new Point();
        display.get().getSize(pt);

        rootScrollView = (ScrollView) findComponentById(ResourceTable.Id_root);

        textFieldHelper.monitorLayoutRefreshed(getWindow(), rootScrollView);
        textFieldHelper.setSoftInputMonitor(new TextFieldHelper.SoftInputMonitor() {
            @Override
            public void onSoftInputVisible(boolean isVisible) {
                Timber.d("onSoftInputVisible() called with: isVisible = [ %s ]", isVisible);
                helloText.setText(String.format("%d:%b",++count,isVisible));
            }
        });

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void bindClick() {
        findComponentById(ResourceTable.Id_btnDialog).setClickedListener(component -> {

            rootScrollView.setLayoutRefreshedListener(v -> {});
            CustomDialog customDialog = new CustomDialog(this);
            customDialog.setTitle("This Is Custom Dialog");
            customDialog.setAutoClosable(true);
            customDialog.setDestroyedListener(() -> textFieldHelper.monitorLayoutRefreshed(getWindow(), rootScrollView));
            customDialog.show();
        });
    }
}
